package com.pkq.singleton;

public class Singleton {
    public static void main(String[] args) {
/*
        System.out.println(Demo.getInstance() == Demo.getInstance());
        System.out.println(Demo.getInstance() == Demo.getInstance());
        System.out.println(Demo.getInstance() == Demo.getInstance());
*/

        for (int i = 0; i < 5; i++) {
            new Thread(() -> Demo.getInstance(), String.valueOf(i)).start();

        }

    }
}

/**
 * @author ピカチュウ(皮卡啾)
 * @date 2021/9/6 18:51
 * @Description: 单例模式
 */
class Demo {
    // 私有的类变量
    private static volatile Demo instance = null;

    // 构造函数私有化
    private Demo() {
        System.out.println(Thread.currentThread().getName() + "线程执行");
    }

    // 公开的类方法
    public static Demo getInstance() {
        // DCL （Double Check Lock）双端检索机制

        if (instance == null) {

            synchronized (Demo.class) {

                if (instance == null) {
                    instance = new Demo();
                }
            }
        }
        return instance;
    }
}
